﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CamlexNET;
using LifeInSharePoint.Blog.Business.DAL;
using LifeInSharePoint.Common;
using LifeInSharePoint.Common.Base;
using Microsoft.SharePoint;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Utilities;

namespace LifeInSharePoint.Blog.Common.WebParts.LISPBlogPosts
{
    [ToolboxItemAttribute(false)]
    public class LISPBlogPosts : BaseWebPart
    {

        #region Private Properties

        private const string POSTLIST = "Pages";
        private const string CONTENTTYPE = "Life In SharePoint Blog Post";
        private string transformedXML = null;
        private bool errorFound = false;
        private string errorMessage = null;
        private int PageNum;
        private int numOfPages;
        private string currentUrl;


        private string postCategory = string.Empty;

        #endregion

        private string _XSLTPath = "/_layouts/LifeInSharePoint.Blog/xslt/Posts.xslt";
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("XSLT Path")]
        [WebDescription("Path the the XSLT")]
        public string XSLTPath
        {
            get { return _XSLTPath; }
            set { _XSLTPath = value; }
        }

        private string _RelSiteUrl = "/blog";
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("Rel Site Url")]
        [WebDescription("Rel Site Url")]
        public string RelSiteUrl
        {
            get { return _RelSiteUrl; }
            set { _RelSiteUrl = value; }
        }

        private int _PageSize = 4;
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("Page Size")]
        [WebDescription("Page Size")]
        public int PageSize
        {
            get { return _PageSize; }
            set { _PageSize = value; }
        }


        protected override void OnInit(EventArgs e)
        {
            this.ChromeType = PartChromeType.None;
            currentUrl = HttpContext.Current.Request.Url.AbsoluteUri;
            postCategory = SPQueryStringHelper.GetQueryStringItem(HttpContext.Current.Request.QueryString, "Category", String.Empty);
            PageNum = SPQueryStringHelper.GetQueryStringItem(HttpContext.Current.Request.QueryString, "page", 1);
            this.ExportMode = WebPartExportMode.All;

            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!string.IsNullOrEmpty(XSLTPath))
            {
                processData();
            }
            else
            {
                errorFound = true;
                errorMessage = "XSLT Path is not Defined - Please edit webpart Properties";
            }

        }

        protected override void CreateChildControls()
        {
            if (!errorFound)
            {
                HtmlGenericControl container = new HtmlGenericControl("Div");
                container.InnerHtml = transformedXML;
                this.Controls.Add(container);
            }
            else
            {
                Label errorMsg = new Label();
                errorMsg.Text = errorMessage;
                this.Controls.Add(errorMsg);
            }

        }


        private void processData()
        {

            List<Post> BlogPosts = new List<Post>();

            BlogPosts = Posts.getPostsListItemCollection();

            if(!string.IsNullOrEmpty(postCategory))
            {
                //Filter List if Category is selected
                var FilteredLists = from posts in BlogPosts
                                    where posts.PostCategory.Contains(postCategory)
                                    select posts;
                BlogPosts = FilteredLists.ToList();
            }


            if (BlogPosts.Count > 0)
            {
                //Create Wrapper DataTable
                DataTable OtherPostDT = new DataTable("Post");

                //Create Auto Increment Column in XML
                DataColumn iIDcolumn = new DataColumn();
                iIDcolumn.DataType = Type.GetType("System.Int32");
                iIDcolumn.AutoIncrement = true;
                iIDcolumn.ColumnName = "iID";
                iIDcolumn.ReadOnly = true;
                iIDcolumn.Unique = true;
                iIDcolumn.AutoIncrementSeed = 1;
                iIDcolumn.AutoIncrementStep = 1;

                //Define Extra Columns for XML
                OtherPostDT.Columns.Add(iIDcolumn);
                OtherPostDT.Columns.Add("ID");
                OtherPostDT.Columns.Add("Title");
                OtherPostDT.Columns.Add("Excerpt");
                OtherPostDT.Columns.Add("MainImage");
                OtherPostDT.Columns.Add("RollupImage");
                OtherPostDT.Columns.Add("PublishedDate");
                OtherPostDT.Columns.Add("Link");
                OtherPostDT.Columns.Add("CommentCount");
                OtherPostDT.Columns.Add("TimeAgo");
                OtherPostDT.Columns.Add("Author");
                OtherPostDT.Columns.Add("Categories");              

                for (int i = 0; i < BlogPosts.Count; i++)
                {
                    Post blogPost = BlogPosts[i];
                    String Categories = blogPost.PostCategory;

                    SPUser _Author = blogPost.ModifiedBy;
                    string Title = blogPost.Title;
                    int ID = blogPost.Id;
                    int CommentCount = blogPost.CommentCount;
                    string Excerpt = blogPost.Excerpt;
                    string RollupImage = blogPost.RollupImage;
                    string MainImage = blogPost.PostImage;
                    DateTime PublishedDate = blogPost.Modified;
                    string Url = blogPost.Url;
                    string TimeAgo = blogPost.TimeAgo;
                    OtherPostDT.Rows.Add(i + 1, ID, Title, Excerpt, MainImage, RollupImage, PublishedDate, Url, CommentCount, TimeAgo, _Author, Categories);
                }

                int FromID = ((PageNum - 1) * PageSize) + 0;
                double ToID = PageNum * PageSize;
                decimal totalRows = OtherPostDT.Rows.Count;
                decimal numOfPages = totalRows / PageSize;

                int PrevPage = PageNum == 1 ? 1 : PageNum - 1;
                int NextPage = PageNum + 1;

                DataTable NavDT = new DataTable("Navigation");
                NavDT.Columns.Add("Pages");

                StringBuilder navlist = new StringBuilder();

                navlist.Append("<ul class='post-paging'>");

                //Calculate Previous Page
                if (PageNum > 1)
                {
                    navlist.Append(string.Format("<li><a href='{0}'>{1}</a></li>", SPQueryStringHelper.SetParameterInQueryString(currentUrl, "page", PrevPage.ToString(), true), "Previous"));
                }

                //Calculate pages numbers
                for (int i = 0; i < numOfPages; i++)
                {
                    string Current = string.Empty;
                    if (PageNum == i + 1)
                    {
                        Current = "class='selected'";
                    }
                    navlist.Append(string.Format("<li {0}><a href='{1}'>{2}</a></li>", Current, SPQueryStringHelper.SetParameterInQueryString(currentUrl, "page", Convert.ToString(i + 1), true), i + 1));
                }

                //Calcualte Next Page
                if (NextPage <= Math.Ceiling(numOfPages))
                {
                    navlist.Append(string.Format("<li><a href='{0}'>{1}</a></li>", SPQueryStringHelper.SetParameterInQueryString(currentUrl, "page", NextPage.ToString(), true), "Next"));
                }

                navlist.Append("</ul>");
                NavDT.Rows.Add(navlist);


                //Create a new DataView and filter it based on page number
                DataView dv;
                dv = OtherPostDT.DefaultView;
                if (PageNum == 1)
                {
                    dv.RowFilter = "iID >= " + FromID + " AND iID <= " + ToID + "";
                }
                else
                {
                    dv.RowFilter = "iID > " + FromID + " AND iID <= " + ToID + "";
                }

                DataSet PostsDS = new DataSet("Posts");
                PostsDS.Tables.Add(dv.ToTable());
                PostsDS.Tables.Add(NavDT);

                //Transform Results
                transformedXML = SPWebPartHelper.ConvertXML(PostsDS.GetXml(), SPContext.Current.Site.Url + XSLTPath);
            }

        }



    }
}